﻿using Microsoft.SharePoint.Administration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CNRSccp.Claims.Helper;

namespace CNRSccp.Claims
{
    public class ClaimProviderConfig : SPPersistedObject
    {
        public const string CnrsccpPersistedObjectID = "8E695389-FF84-4F58-AC23-2049EF4C43F8";
        public const string CnrsccpPersistedObjectName = "CnrsccpConfig";

        [Persisted]
        public string DatabaseServer;

        [Persisted]
        public string DatabaseUserName;

        [Persisted]
        public string DatabasePassword;

        
        public ClaimProviderConfig(SPPersistedObject parent)
            : base(CnrsccpPersistedObjectName, parent)
        {
        }

        public ClaimProviderConfig()
        {
        }

        protected override bool HasAdditionalUpdateAccess()
        {
            return false;
        }

        public static ClaimProviderConfig GetFromConfigDB
        {
            get
            {
                SPPersistedObject parent = SPFarm.Local;
                try
                {
                    return parent.GetChild<ClaimProviderConfig>(CnrsccpPersistedObjectName);
                }
                catch (Exception ex)
                {
                    ClaimsHelper.LogToULS(String.Format("Error while retrieving SPPersistedObject {0}: {1}", CnrsccpPersistedObjectName, ex.Message), TraceSeverity.Unexpected, EventSeverity.Error);
                }
                return null;
            }
        }

        /// <summary>
        /// Create the persisted object that contains Database connexion configuration of Cnrsccp.
        /// </summary>
        public static ClaimProviderConfig CreatePersistedObject()
        {
            ClaimProviderConfig PersistedObject = new ClaimProviderConfig(SPFarm.Local);
            PersistedObject.Id = new Guid(CnrsccpPersistedObjectID);
            PersistedObject = GetDefaultSettings(PersistedObject);
            try
            {
                PersistedObject.Update();
            }
            catch (NullReferenceException nullex)
            {
                // This exception occurs if an older version of the persisted object lives in the config database with a schema that doesn't match current one
                string stsadmcmd = String.Format("SELECT * FROM Objects WHERE Id LIKE '{0}'", CnrsccpPersistedObjectID);
                string error = String.Format("Unable to create PersistedObject {0}. This usually occurs because a persisted object with the same Id is used by another assembly (could be a previous version). Object is impossible to update or delete from Object Model unless you add the missing assembly to the GAC. You can see this object by running this query: \"{1}\"", PersistedObject.Name, stsadmcmd);

                ClaimsHelper.LogToULS(
                   error,
                   TraceSeverity.Unexpected,
                   EventSeverity.Error);

                // Try to delete it... but OM doesn't manage to get the object
                SPPersistedObject staleObject = SPFarm.Local.GetObject(new Guid(CnrsccpPersistedObjectID));
                if (staleObject != null)
                {
                    staleObject.Delete();
                    PersistedObject.Update();
                }
                else
                {
                    throw new Exception(error, nullex);
                }
            }

            ClaimsHelper.LogToULS(
                String.Format("Created PersistedObject {0} with Id {1}", PersistedObject.Name, PersistedObject.Id),
                TraceSeverity.Medium,
                EventSeverity.Information);

            return PersistedObject;
        }

        /// <summary>
        /// Return Default configuration of Cnrsccp. 
        /// </summary>
        /// <param name="PersistedObject"></param>
        /// <returns></returns>
        public static ClaimProviderConfig GetDefaultSettings(ClaimProviderConfig PersistedObject)
        {
            // merge from SP6
			// TODO: Should not exit unless for test purpose!
			PersistedObject.DatabaseServer = "SP6";
            PersistedObject.DatabaseUserName = "cnrsClaims";
            PersistedObject.DatabasePassword = "4aStr0FF.";            
            return PersistedObject;
        }
    }
}
